package com.shujia.source

import java.sql.{Connection, DriverManager, PreparedStatement, ResultSet}

import org.apache.flink.configuration.Configuration
import org.apache.flink.streaming.api.functions.source.{RichSourceFunction, SourceFunction}
import org.apache.flink.streaming.api.scala._

object Demo3MysqlSource {

  def main(args: Array[String]): Unit = {

    val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment

    val mysqlDS: DataStream[AdminCode] = env
      .addSource(new MysqlSource)

    val countDS: DataStream[(String, Int)] = mysqlDS.map(ac => (ac.cituName,1))
        .keyBy(_._1)
        .sum(1)

    countDS.print()

    env.execute()


  }

}

case class AdminCode(provName: String, cituName: String, countyName: String)

class MysqlSource extends RichSourceFunction[AdminCode]{

  var conn: Connection = _
  var ps: PreparedStatement = _
  var rs: ResultSet = _

  /**
    * open方法在run方法执行之前执行，只执行一次
    * @param parameters
    */
  override def open(parameters: Configuration): Unit = {

    //加载驱动
    Class.forName("com.mysql.jdbc.Driver")
    //获取连接
    conn = DriverManager.getConnection("jdbc:mysql://master:3306/tour","root","123456")

  }

  /**
    * open 方法; 在run 方法之后执行，只执行一次
    */
  override def close(): Unit = {
    rs.close()
    ps.close()
    conn.close()
  }

  override def run(ctx: SourceFunction.SourceContext[AdminCode]): Unit = {

    ps = conn.prepareStatement("select prov_name,city_name,county_name from admin_code")

    rs = ps.executeQuery()

    while (rs.next()){

      val prov_name: String = rs.getString("prov_name")
      val city_name: String = rs.getString("city_name")
      val county_name: String = rs.getString("county_name")

      //发送到下游
      ctx.collect(AdminCode(prov_name,city_name,county_name))
    }

  }

  override def cancel(): Unit = ???
}
